package com.demo.upload.controller;


import com.demo.upload.common.Res;
import com.demo.upload.common.Result;
import com.demo.upload.dto.FileChunkDto;
import com.demo.upload.service.FileChunkService;
import com.demo.upload.service.FileStorageService;
import com.demo.upload.vo.CheckResultVo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 文件存储controller
 */
@RestController
@RequestMapping("fileStorage")
public class FileStorageController {
    @Resource
    private FileStorageService fileStorageService;
    @Resource
    private FileChunkService fileChunkService;

    /**
     * 校验接口，即上传前，先根据本接口查询一下 服务器是否存在该文件
     */
    @GetMapping("/upload")
    public Result<CheckResultVo> checkUpload(FileChunkDto dto) {
        return Res.ok(fileChunkService.check(dto));
    }

    /**
     * 上传接口
     */
    @PostMapping("/upload")
    public Result<Boolean> upload(FileChunkDto dto, HttpServletResponse response) {
        try {
            Boolean status = fileStorageService.uploadFile(dto);
            if (status) {
                return Res.ok();
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return Res.error("上传失败");
            }
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return Res.error("上传失败");
        }
    }

}

